package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Class Parser based on the generic solution to obtaining dynamic data from yahoo
 * weather.
 * 
 * @author Rasmus Stjerne, Joachim Lindholm, Daniel Gramstrup, Pamela Pedersen
 * 
 */
public class Parser {


	
	/**
	 * Static method to obtain the dynamic wind chill factor from the local area
	 * @return double value of the wind chill
	 */
	public static double parseWindChill() {
		// Create a URLConnection object for a URL
		URL url = null;
		double windchill = 0;
		try {
			url = new URL(
					"http://weather.yahooapis.com/forecastrss?w=28583793&u=c");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			URLConnection conn = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String inputLine;
			// Modified to select the wind chill
			String matchStr = "<yweather:wind chill=\"";
			while ((inputLine = in.readLine()) != null) {
				if (inputLine.startsWith(matchStr)) {
					String chill = inputLine.substring(matchStr.length(),
							inputLine.indexOf('"', matchStr.length()));
					windchill = Double.parseDouble(chill);
				}
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return windchill;
	}

	/**
	 * Calculate the CCUSEFACTOR based on the formula:
	 * CCUSERFACTOR = 1 + (100 - Wind Chill) / 100
	 * @return the CCUSEFACTOR
	 */
	public static double computeCCUSEFACTOR() {
		return 1 + ((100 - parseWindChill()) / 100);
	}
}
